package com.bwie.gateway.filters;

import cn.hutool.core.util.ObjectUtil;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.exception.BusinessException;
import com.bwie.common.pojo.po.UserPo;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private IgnoreWhiteConfig ignoreWhiteConfig;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //开放路径
        List<String> whites = ignoreWhiteConfig.getWhites();
        //前端访问路径
        String path = exchange.getRequest().getURI().getPath();
        //相同放行
        if(StringUtils.matches(path,whites)){
            return chain.filter(exchange);
        }
        //获取token
        String token = exchange.getRequest().getHeaders().getFirst(TokenConstants.TOKEN);
        //如果token为空，抛出异常
        if(StringUtils.isBlank(token)){
            throw new BusinessException(Result.error("token为空"));
        }

        try {
            //解析token
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            //解析token失败，抛出异常
            throw new BusinessException(Result.error("token为空"));
        }
        //获取用户key
        String userKey = JwtUtils.getUserKey(token);
        //从redis中获取用户信息
        UserPo user = (UserPo) redisTemplate.opsForValue().get(JwtConstants.USER_KEY + userKey);
        //如果用户信息为空，抛出异常
        if(ObjectUtil.isEmpty(user)){
            throw new BusinessException(Result.error("用户不存在"));
        }
        //继续执行过滤器链
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
